package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionDao;
import com.itheima.pojo.Permission;
import entity.PageResult;
import entity.QueryPageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

/**
 * @Description:
 * @Author: yp
 */
@Service(interfaceClass = PermissionService.class)
@Transactional
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionDao permissionDao;

    /**
     * 根据角色id查询权限
     * @param roleId
     * @return
     */
    @Override
    public Set<Permission> findByRoleId(Integer roleId) {
        return permissionDao.findByRoleId(roleId);
    }


    //权限分页查询:
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //1.调用MyBatis分页插件方法(自动帮我们做分页)  ThreadLocal, MyBatis拦截器
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        //2.调用Dao
        Page<Permission> page = permissionDao.selectConditions(queryPageBean.getQueryString());
        PageResult pageResult = new PageResult(page.getTotal(), page.getResult());
        return pageResult;
    }

    //新增权限
    @Override
    public void add(Permission permission) {
        permissionDao.add(permission);
    }

    //编辑 权限表单回显
    @Override
    public Permission findById(Integer id) {
        return permissionDao.findById(id);
    }

    //更新权限
    @Override
    public void edit(Permission permission) {
        permissionDao.edit(permission);
    }

    //删除权限
    @Override
    public void delete(Integer id) {
        //1.判断当前的检查项是否被检查组引用到了
        long count =  permissionDao.findCountByCheckItemId(id);
        if(count > 0){
            //2.有引用dao, 抛出异常
            throw new RuntimeException("此检查项被引用到了,不能删除");
        }

        //3.没有引用,调用Dao 删除
        permissionDao.deleteById(id);
    }


    //角色需要的权限信息
    @Override
    public List<Permission> findAll() {
        return permissionDao.findAll();
    }


}
